# -*- coding: utf-8 -*-

from __future__ import print_function

import os
import sys
from pathlib import Path
from subprocess import PIPE, Popen

pyuic_path = os.environ.get(
    'PYUIC', r'E:\Miniconda\envs\py36\Scripts\pyuic5.exe')


def ui_to_py(path):
    if path.is_file():
        file_list = [str(path)]
    elif path.is_dir():
        file_list = path.rglob('*.ui')
    else:
        return

    for _f in file_list:
        file = Path(_f)
        py_file = file.with_name(file.stem + '.py')
        cmd = '"{}" -o "{}" "{}"'.format(pyuic_path, py_file, _f)
        proc = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
        sout, serr = map(lambda s: s.decode('utf8'), proc.communicate())

        if sout:
            print('[STDOUT] {}: {}'.format(_f, sout))
        if serr:
            print('[STDERR] {}: {}'.format(_f, serr))


if __name__ == '__main__':
    for arg in sys.argv[1:]:
        ui_to_py(Path(arg))
